package com.components.headerrecycler

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * @Author LuoKun
 * @Des 带头部的自定义RecyclerView
 * 用例：在不需要上下刷新的时候统一用这个类，方便管理
 */
class HeaderRecyclerView : RecyclerView {

    private lateinit var mAdapter: HeaderViewAdapter

    fun getMAdapter(): HeaderViewAdapter? {
        if (this::mAdapter.isLateinit) {
            return mAdapter
        }
        return null
    }

    constructor(context: Context) : super(context) {
        wrapHeaderAdapter()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        wrapHeaderAdapter()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        wrapHeaderAdapter()
    }

    override fun setLayoutManager(layout: LayoutManager?) {
        if (layout is GridLayoutManager && layout !is HeaderViewGridLayoutManager) {
            super.setLayoutManager(HeaderViewGridLayoutManager(context, layout.spanCount, mAdapter))
        } else {
            super.setLayoutManager(layout)
        }
    }

    private fun wrapHeaderAdapter() {
        mAdapter = HeaderViewAdapter(super.getAdapter())
        super.setAdapter(mAdapter)
    }

    override fun setAdapter(adapter: Adapter<*>?) {
        mAdapter.setAdapter(adapter as Adapter<ViewHolder>)
    }

    override fun getAdapter(): Adapter<*>? {
        return mAdapter.getAdapter()
    }

    /**获取HeaderView个数*/
    fun getHeaderCount(): Int {
        return mAdapter.getHeadersCount()
    }

    /**获取FooterView的个数*/
    fun getFooterCount(): Int {
        return mAdapter.getFootersCount()
    }

    /**添加HeaderView*/
    fun addHeaderView(view: View) {
        mAdapter.addHeaderView(view)
    }

    /**删除HeaderView*/
    fun removeHeaderView(view: View): Boolean {
        return mAdapter.removeHeaderView(view)
    }

    /**添加FooterView*/
    fun addFooterView(view: View) {
        mAdapter.addFooterView(view)
    }

    /**删除FooterView*/
    fun removeFooterView(view: View): Boolean {
        return mAdapter.removeFooterView(view)
    }
}